# 定义序列化器, 用于校验
from django_redis import get_redis_connection
from rest_framework import serializers

class RegisterSMSCodeSerializer(serializers.Serializer):
    """
    校验验证码和image_code_id
    """
    text = serializers.CharField(label='用户输入的验证码',max_length=4,min_length=4,required=True)
    image_code_id = serializers.UUIDField(label='验证码唯一性id')

    # validate进行判断
    def validate(self, attrs):
        # 获取数据
        text = attrs['text']
        image_code_id = attrs['image_code_id']
        # 链接redis
        redis_conn = get_redis_connection('code')
        redis_text = redis_conn.get('img_%s' % image_code_id)
        # 判断是否存在,根据键删除对应存储的图片验证码
        if redis_text is None:
            raise serializers.ValidationError('验证码过期')
        # 删除存储的验证码
        redis_conn.delete('img_%s' % image_code_id)
        # 获取到的与数据库的对比，redis的值为bytes
        if text.lower() != redis_text.decode().lower():
            raise serializers.ValidationError('验证码不一致')
        # 返回attr
        return attrs